package org.example.service;

import com.alibaba.fastjson2.JSONObject;
import org.example.gamemodel.World;

import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

public class GameServer {
    int maxWorldNum=5;
    int maxPlayerNum=32;
    public List<World> worldList=new LinkedList<>();

    public GameServer(){}

    public String PlayerJoinIn(String player, Socket player_socket){
        if(worldList.size()==0){
            World world=new World(worldList.size());
            world.addPlayer(player,player_socket);
            worldList.add(world);
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("response","success");
            jsonObject.put("world_id",world.id);
            return jsonObject.toJSONString();
        }else{
            for(World world:worldList){
                if(world.player_sockets.size()<maxPlayerNum){
                    world.addPlayer(player,player_socket);
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("response","success");
                    jsonObject.put("world_id",world.id);
                    return jsonObject.toJSONString();
                }
            }
            if(worldList.size()<maxWorldNum){
                World world=new World(worldList.size());
                world.addPlayer(player,player_socket);
                worldList.add(world);
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("response","success");
                jsonObject.put("world_id",world.id);
                return jsonObject.toJSONString();
            }else{
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("response","server full");
                return jsonObject.toJSONString();
            }
        }
    }

    public void SendFrame(int world_id,String user, JSONObject frame){
        worldList.get(world_id).SendFrame(user,frame);
    }

    public String PlayerRelink(int world_id,String user, Socket socket){
        worldList.get(world_id).ReLink(user,socket);
        return "success";
    }
}
